<script lang="ts" setup>
import type { CheckedSelectTree } from '#/api';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { ElTree } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import {
  addTenantPackage,
  editTenantPackage,
  menuTreeSelect,
} from '#/api/platform/systenant/package';
import { $t } from '#/locales';

import { formSchema } from '../data';

const emit = defineEmits(['success']);

const menuRef = ref<any>({});
const menuTree = ref<CheckedSelectTree>();
const loading = ref(false);

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  schema: formSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = await formApi.getValues();

    data.menuIds = menuRef?.value.getCheckedKeys();

    try {
      await (data?.packageId
        ? editTenantPackage(data)
        : addTenantPackage(data));
      modalApi.close();
      emit('success');
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData();

    modalApi.setState({
      title: data.packageId
        ? $t('ui.actionTitle.edit', [$t('tenant.package.package')])
        : $t('ui.actionTitle.create', [$t('tenant.package.package')]),
    });
    if (data) {
      formApi.setValues(data, false);
    }
    await loadMenu(data?.packageId);
  },
});

async function loadMenu(packageId: string) {
  loading.value = true;
  try {
    menuTree.value = await menuTreeSelect(packageId);
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <Modal>
    <Form class="mx-4">
      <template #menuIds>
        <ElTree
          class="w-full"
          ref="menuRef"
          v-loading="loading"
          :data="menuTree?.selectTrees ?? []"
          :default-checked-keys="menuTree?.checkedKeys"
          show-checkbox
          node-key="id"
          :props="{
            label: 'label',
            children: 'children',
          }"
        >
          <template #node="{ value }">
            <IconifyIcon v-if="value.icon" :icon="value.icon" />
            {{ $t(value.label) }}
          </template>
        </ElTree>
      </template>
    </Form>
  </Modal>
</template>

<style>
.el-tree {
  border: 1px solid #ebeef5; /* 添加边框 */
  border-radius: 8px; /* 可选：添加圆角 */
}
</style>
